package com.hy.lightning.ds.jdbc.datasources;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.hy.lightning.ds.JdbcDataSource;
import com.zaxxer.hikari.HikariDataSource;

public class HikariCPDataSource implements JdbcDataSource {

	/**
	 * redis数据库连接池
	 */
	private static Map<String, HikariDataSource> dataSourceMap = new ConcurrentHashMap<>();
	
	private static volatile boolean isInitJedisPool = false;
	
	/**
	 * 初始化数据库连接池配置
	 */
	static {
		if(!isInitJedisPool) {
			for(Entry<String, JdbcConf> entry : conf_map.entrySet()) {
				JdbcConf conf = entry.getValue();
				if(conf != null) {
					try {
						HikariDataSource dataSource = getDataSource(conf);
						dataSourceMap.put(conf.getKey(), dataSource);
					} catch (PropertyVetoException e) {
						e.printStackTrace();
					}
				}
			}
			isInitJedisPool = true;
		}
		
	}
	
	private static HikariDataSource getDataSource(JdbcConf configuration) throws PropertyVetoException {
		HikariDataSource dataSource = null;
		if(configuration.getDataSource() != null) dataSource = (HikariDataSource) configuration.getDataSource();
		else dataSource = new HikariDataSource();
		String url = configuration.getUrl();
		dataSource.setJdbcUrl(String.format(url, configuration.getIp(), configuration.getPort(), configuration.getName()));
		dataSource.setDriverClassName(configuration.getDriverClassName());
		dataSource.setUsername(configuration.getUsername());
		dataSource.setPassword(configuration.getPassword());
		return dataSource;
	}
	
	@Override
	public Connection getConnection(String key) {
		if(dataSourceMap.containsKey(key)) {
			try {
				return dataSourceMap.get(key).getConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public Connection getConnection() {
		// TODO Auto-generated method stub
		return getConnection("local");
	}
}
